package com.fulihui.systemcore.service;

import com.fulihui.systemcore.api.WechatTokenService;
import com.fulihui.systemcore.biz.shard.WechatTokenManager;
import com.fulihui.systemcore.enums.EnvTypeEnum;
import com.fulihui.systemcore.enums.WechatTokenTypeEnum;
import com.fulihui.systemcore.request.wechat.WechatTokenRequest;
import com.fulihui.systemcore.response.wechat.WechatTokenResult;
import org.apache.dubbo.config.annotation.Service;
import org.near.servicesupport.error.CommonServiceErrorEnum;
import org.near.servicesupport.error.InvokeServiceException;
import org.near.servicesupport.result.ResultBuilder;
import org.near.toolkit.common.EnumUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * Created by Willard.Hu on 2016/4/11.
 */
@Service(version = "1.0.0")
public class WechatTokenServiceImpl implements WechatTokenService {
    private static final Logger LOG = LoggerFactory.getLogger(WechatTokenServiceImpl.class);
    @Autowired
    private WechatTokenManager wechatTokenManager;
    @Value("${product.env}")
    private String productEnv;

    @Override
    public WechatTokenResult getToken(WechatTokenRequest request) {
        WechatTokenTypeEnum tokenType = EnumUtil.queryByCode(request.getTokenType(),
                WechatTokenTypeEnum.class);
        if (tokenType == null) {
            LOG.error("微信token类型错误{}", request.getTokenType());
            throw new InvokeServiceException(CommonServiceErrorEnum.REQUEST_PARAMETER_ERROR);
        }

        if (EnvTypeEnum.DEV.getCode().equals(productEnv)) {
            LOG.info("获取token，DEV环境路由到STABLE环境");
            return queryByStableDB(request);
        }

        String token = wechatTokenManager.getToken(request.getAppid(), request.getSecret(),
                tokenType);
        WechatTokenResult result = ResultBuilder.succ(WechatTokenResult.class);
        result.setToken(token);
        return result;
    }

    /**
     * 开发、测试环境同时竞争 wechat token 导致两边很快都失效，
     * 现在将开发环境获取 token 会直接读取测试库的数据，由测试环境处理定时刷新
     *
     * @param request {@link WechatTokenRequest}
     * @return {@link WechatTokenResult}
     */
    private static WechatTokenResult queryByStableDB(WechatTokenRequest request) {
        String url = "jdbc:mysql://192.168.1.45:3306/systemcore_test";
        String user = "systemcore_ro";
        String passwd = "systemcore_ro";

        try (Connection conn = DriverManager.getConnection(url, user, passwd)) {
            String sql = "select token from sys_wechat_token where appid=? and token_type=?";
            String token = null;
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, request.getAppid());
            pstmt.setString(2, request.getTokenType());
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                token = rs.getString("token");
            }
            WechatTokenResult wechatTokenResult = ResultBuilder.succ(WechatTokenResult.class);
            wechatTokenResult.setToken(token);
            return wechatTokenResult;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
